package com.yunyilian8.www.jokeapp.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.superplayer.library.SuperPlayer;
import com.yunyilian8.www.jokeapp.R;
import com.yunyilian8.www.jokeapp.activity.HomeActivity;
import com.yunyilian8.www.jokeapp.adapter.VideoPlayListAdapter;
import com.yunyilian8.www.jokeapp.base.BaseFragment;
import com.yunyilian8.www.jokeapp.bean.AnyEventType;
import com.yunyilian8.www.jokeapp.bean.FileNameBean;
import com.yunyilian8.www.jokeapp.bean.SDCardFilePathBean;
import com.yunyilian8.www.jokeapp.bean.ShareVideoBean;
import com.yunyilian8.www.jokeapp.bean.VideoFileNameBean;
import com.yunyilian8.www.jokeapp.utils.Contants;
import com.yunyilian8.www.jokeapp.utils.DialogUtils;
import com.yunyilian8.www.jokeapp.utils.EventBusEvents;
import com.yunyilian8.www.jokeapp.utils.FileUtils;
import com.yunyilian8.www.jokeapp.utils.SDCardUtils;
import com.yunyilian8.www.jokeapp.utils.SerializeManager;
import com.yunyilian8.www.jokeapp.utils.StringUtils;
import com.yunyilian8.www.jokeapp.utils.ToastUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;

import static com.yunyilian8.www.jokeapp.utils.SerializeManager.loadFile;


/*****************************************************
 * author:      wyb
 * email:       276698048@qq.com
 * date:        2017/2/10  14:13
 * description: 视频直播fragment
 *****************************************************/
public class VideoPlayFragment extends BaseFragment implements SuperPlayer.OnNetChangeListener {

    public static final int FILE_SELECT_CODE = 1000;
    @InjectView(R.id.view_super_player)
    SuperPlayer mSuperPlayer;
    @InjectView(R.id.lv_type)
    ListView mLvFileName;
    @InjectView(R.id.lv_program)
    ListView mLvVideoName;
    @InjectView(R.id.tv)
    TextView mTv;
    @InjectView(R.id.iv_video_image)
    ImageView mIv;
    @InjectView(R.id.pb_video_loading)
    ProgressBar mPr;
    @InjectView(R.id.fl_night_mode)
    FrameLayout mFlNightMode;
    @InjectView(R.id.fl_layout_lodding)
    RelativeLayout mRlLodding;
    @InjectView(R.id.tv_list)
    TextView mTvList;
    @InjectView(R.id.menu_yellow)
    FloatingActionMenu mMenu;
    @InjectView(R.id.fab1)
    FloatingActionButton mFab1;
    @InjectView(R.id.fab2)
    FloatingActionButton mFab2;
    @InjectView(R.id.fl_cloud)
    FrameLayout mFlCloud;

    private View mView;
    boolean mThreadStata = true;
    private static boolean DIALOG_SHOW = false;
    //节目类型列表数据
    private List<FileNameBean> mFileNameList = new ArrayList();
    //节目列表数据
    private List<VideoFileNameBean> mVideoFileNameList = new ArrayList();
    private String mFileName = "";
    private String mFilePathName = "";
    public int mTypePosition;
    public int mTVListPosition;
    //视频播放地址
    private String mURL;
    //记录视频播放进度
    private int mCurrentPosition;
    private VideoPlayListAdapter mFileNameAdapter;
    private VideoPlayListAdapter mVideoFileNameAdapter;
    String[] mFiles;
    //默认白天模式
    boolean isNight = false;
    boolean fabOpened = false;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_video_play, container);
        ButterKnife.inject(this, mView);
        EventBus.getDefault().register(this);

        try {
            // 获得Assets中所有文件,得到该目录下所有文件名称
            mFiles = this.getResources().getAssets().list("video");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //设置listView的adapter以及监听
        setListView();
        //初始化数据
        initData();
        //初始化视频播放器
        initVideo();
        //初始化menue
        initFab();

        return mView;
    }

    private void initFab() {

        mMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
            @Override
            public void onMenuToggle(boolean opened) {
                if (opened) {
                    if (!isNight) {
                        setFlCloud(true);
                    }
                } else {
                    if (!isNight) {
                        setFlCloud(false);
                    }
                }
            }
        });
        mFab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换白夜间
                mMenu.close(true);

                //设置夜白天模式
                setCheckBoxChecked();
            }
        });
        mFab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加文件
                mMenu.close(true);

                //去添加文件
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("file/*");
                startActivityForResult(intent, FILE_SELECT_CODE);
            }
        });
        mFlCloud.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMenu.close(true);
                setFlCloud(false);
            }
        });
    }

    private void setFlCloud(boolean open) {
        if (open) {
            mFlCloud.setVisibility(View.VISIBLE);
            mFlCloud.setClickable(true);
            AlphaAnimation animation = new AlphaAnimation(0, 0.9f);
            animation.setDuration(300);
            mFlCloud.setAnimation(animation);
            fabOpened = true;
        } else {
            mFlCloud.setVisibility(View.GONE);
            mFlCloud.setClickable(false);
            AlphaAnimation animation = new AlphaAnimation(0.9f, 0);
            animation.setDuration(300);
            mFlCloud.setAnimation(animation);
            fabOpened = false;
        }
    }


    /**
     * 设置checkBox的状态,并设置夜间模式和白天模式切换
     */
    private void setCheckBoxChecked() {
        isNight = !isNight;
        if (fabOpened) {
            setFlCloud(false);
        }
        if (isNight) {
            //夜间模式
            mFlNightMode.setBackgroundColor(getResources().getColor(R.color.color_646464_alpha));
            //通知底部夜间模式
            EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.NIGHT_MODE_ON, null));
            mFab1.setLabelText("白天模式");
        } else {
            //白天模式
            mFlNightMode.setBackgroundColor(getResources().getColor(R.color.transparent));
            //通知底部白天模式
            EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.NIGHT_MODE_OFF, null));
            mFab1.setLabelText("夜间模式");
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {

        SDCardFilePathBean sdCardBean = (SDCardFilePathBean) loadFile(Contants.SDCardPathBean);

        if (null == sdCardBean) {
            //第一次进入app,还没有创建本地file
            if (!SDCardUtils.hasSdcard()) {
                ToastUtil.showToast(mAppContext, "没有存储卡");
                return;
            }
            sdCardBean = new SDCardFilePathBean();
            String[] files;
            try {
                // 获得Assets一共有多少文件
                files = this.getResources().getAssets().list("video");
            } catch (IOException e1) {
                return;
            }
            //默认的选中的文件名item
            mFilePathName = "video" + "/" + files[0];
            //将assets文件信息存入list中
            for (int x = 0; x < files.length; x++) {
                FileNameBean bean = new FileNameBean();
                bean.setName(files[x]);
                if (x == 0) {
                    //设置默认的第一个目录为收藏目录
                    bean.setUnfolded(true);
                } else {
                    bean.setUnfolded(false);
                }
                bean.setAssetsFile(true);
                mFileNameList.add(bean);
            }
            sdCardBean.setmList(mFileNameList);

            //将封装的bean存入本地.
            SerializeManager.saveFile(sdCardBean, Contants.SDCardPathBean);
        } else {
            //读取本地文件中缓存的数据
            SDCardFilePathBean bean = (SDCardFilePathBean) SerializeManager.loadFile(Contants.SDCardPathBean);
            mFileNameList.clear();
            mFileNameList.addAll(bean.getmList());
        }

        //默认的节目列表名称
        initDefaultData();
        mTv.setText("当前暂无观看");
        mFileNameAdapter.notifyDataSetChanged();
        //刷新节目列表
        mVideoFileNameAdapter.notifyDataSetChanged();
    }

    /**
     * 读取txt文件,并将文件数据解析成对象存入list中
     *
     * @param fileName
     * @param boo      是不是assets目录
     */
    private void readFile(String fileName, String filePath, boolean boo) {
        mVideoFileNameList.clear();
        InputStream open = null;
        //默认不是乱码
        boolean isMessyCode = false;
        try {
            BufferedReader dataIO = null;
            InputStream stream = null;
            if (boo) {
                AssetManager manager = getActivity().getAssets();
                open = manager.open("video/" + fileName);
                dataIO = new BufferedReader(new InputStreamReader(open, "UTF-8"));
            } else {
                stream = new FileInputStream(filePath);

                //默认的编码方式
                dataIO = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                String strLine = null;
                while ((strLine = dataIO.readLine()) != null && !isMessyCode) {
                    String name = strLine.split(",")[0];
                    //判断是不乱码
                    if (StringUtils.isMessyCode(mCtx, name)) {
                        //说明是乱码
                       isMessyCode = true;
                    }
                }

                stream.close();
                dataIO.close();
                //根据不同的编码重新读取文件数据
                readSDCardFile(filePath, isMessyCode);
                return;
            }

            String strLine = null;
            while ((strLine = dataIO.readLine()) != null) {
                VideoFileNameBean bean = new VideoFileNameBean();
                String name = strLine.split(",")[0];
                String url = strLine.split(",")[1];
                bean.setName(name);
                bean.setURL(url);
                bean.setUnfolded(false);

                //判断是不是收藏的节目
                bean.setCollect(isUniform(name));
                mVideoFileNameList.add(bean);
            }
            dataIO.close();
            if (null != open) {
                open.close();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ToastUtil.showToast(mAppContext, "文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showToast(mAppContext, "文件格式错误");
        }
    }

    private void readSDCardFile(String filePath, boolean isMessyCode) throws IOException {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(filePath);
            BufferedReader dataIO = null;

            //默认的编码方式
            try {
                if (!isMessyCode) {
                    //默认的编码方式
                    dataIO = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                } else {
                    dataIO = new BufferedReader(new InputStreamReader(stream, "GBK"));
                }
                String strLine = null;
                while ((strLine = dataIO.readLine()) != null) {
                    VideoFileNameBean bean = new VideoFileNameBean();
                    String name = strLine.split(",")[0];
                    String url = strLine.split(",")[1];

                    bean.setName(name);
                    bean.setURL(url);
                    bean.setUnfolded(false);

                    //判断是不是收藏的节目
                    bean.setCollect(isUniform(name));
                    mVideoFileNameList.add(bean);
                }
                stream.close();
                dataIO.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            ToastUtil.showToast(mAppContext,"请检测文件格式");
            e.printStackTrace();
        }

    }

    /**
     * 判断是不是收藏的节目
     *
     * @param str
     * @return
     */
    private boolean isUniform(String str) {
        //获取本地文件中的对象数据
        ShareVideoBean shareVideoBean = (ShareVideoBean) SerializeManager.loadFile(Contants.RadioCollect);
        //如果sp中没有存在的对象,说明并没有收藏的目录,返回fasle
        if (null == shareVideoBean) {
            return false;
        }

        //如果sp中存在对象,就获取它中的list集合.遍历集合,并判断是不是和传递的srt字符串相等
        List<VideoFileNameBean> list = shareVideoBean.getList();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getName().trim().equals(str)) {
                //如果相同,返回true
                return true;
            }
        }
        return false;
    }

    /**
     * 加载默认收藏的节目列表
     */
    private void initDefaultData() {
        mVideoFileNameList.clear();
        ShareVideoBean shareVideoBean = (ShareVideoBean) loadFile(Contants.RadioCollect);
        if (null == shareVideoBean) {
            return;
        }
        List<VideoFileNameBean> list = shareVideoBean.getList();
        for (int i = 0; i < list.size(); i++) {
            VideoFileNameBean bean = list.get(i);
            VideoFileNameBean nameBean = new VideoFileNameBean();
            nameBean.setCollect(true);
            nameBean.setName(bean.getName().trim());
            nameBean.setURL(bean.getURL().trim());
            mVideoFileNameList.add(nameBean);
        }
    }

    /**
     * 初始化视频播放器
     */
    private void initVideo() {
        mSuperPlayer.setScaleType(SuperPlayer.SCALETYPE_FITXY);
        mSuperPlayer.setLive(true);//true：表示直播地址；false表示点播地址
        mSuperPlayer.setPlayerWH(0, mSuperPlayer.getMeasuredHeight());//设置竖屏的时候屏幕的高度，如果不设置会切换后按照16:9的高度重置
        initVideoPlayListener();
    }

    private void setListView() {
        mFileNameAdapter = new VideoPlayListAdapter(mCtx, mFileNameList, 1);
        mVideoFileNameAdapter = new VideoPlayListAdapter(mCtx, mVideoFileNameList, 2);

        mLvFileName.setAdapter(mFileNameAdapter);
        mLvVideoName.setAdapter(mVideoFileNameAdapter);

        //节目类型列表的点击监听
        mFileNameAdapter.setListener(new VideoPlayListAdapter.VideoListListener() {
            @Override
            public void chooseItem(final int position, int type, String fileName, String url) {

                mTypePosition = position;
                mRlLodding.setVisibility(View.VISIBLE);

                //设置节目类型列表item点击状态
                setTypeListState();
                mFileNameAdapter.notifyDataSetChanged();

                //加载默认的收藏列表数据
                if (position == 0) {
                    //加载默认的收藏列表数据
                    initDefaultData();
                } else {
                    //根据类型,加载不同节目列表数据
                    FileNameBean fileNameBean = mFileNameList.get(position);
                    readFile(fileNameBean.getName(), fileNameBean.getPath(), fileNameBean.isAssetsFile());
                }

                //刷新节目列表
                mVideoFileNameAdapter.notifyDataSetChanged();
                mRlLodding.setVisibility(View.GONE);
            }

            @Override
            public void longClick(final int position, int type, String programFileName, final String filePath) {

                //如果是assets中的文件,就提示不可以删除
                if (position <= 9) {
                    //说明是assets文件
                    ToastUtil.showToast(mAppContext, "您只可以删除自己添加的文件!");
                    return;
                }

                //如果是本地添加的文件,就删除提示?
                DialogUtils.showDialog(getActivity(), "删除文件", "确定要删除该文件吗?", new DialogUtils.ShowDialogListener() {
                    @Override
                    public void onFixed() {
                        //根据路径,删除sp中的路径字符串.
                        SDCardFilePathBean sdCardBean = (SDCardFilePathBean) loadFile(Contants.SDCardPathBean);
                        List<FileNameBean> fileNameBeenList = null;
                        if (null != sdCardBean) {
                            fileNameBeenList = sdCardBean.getmList();
                            for (int i = 0; i < fileNameBeenList.size(); i++) {
                                if (filePath.equals(fileNameBeenList.get(i).getPath())) {
                                    fileNameBeenList.remove(position);
                                }
                            }
                        }
                        //重新存入到本地文件保存.
                        sdCardBean.setmList(fileNameBeenList);
                        SerializeManager.saveFile(sdCardBean, Contants.SDCardPathBean);

                        //先清空再添加
                        mFileNameList.clear();
                        mFileNameList.addAll(fileNameBeenList);
                        mFileNameAdapter.notifyDataSetChanged();
                        ToastUtil.showToast(mAppContext, "删除成功");
                    }

                    @Override
                    public void onDismiss() {
                        //取消
                    }
                });
            }
        });

        //电视列表item的点击监听
        mVideoFileNameAdapter.setListener(new VideoPlayListAdapter.VideoListListener() {
            @Override
            public void chooseItem(int position, int type, String programFileName, String url) {
                mTVListPosition = position;
                //全局url
                mURL = url;
                //设置loadding显示
                mPr.setVisibility(View.VISIBLE);

                if (mSuperPlayer != null && mSuperPlayer.isPlaying()) {
                    mSuperPlayer.onDestroy();
                }
                //设置电视列表item的点击状态
                setListItemState();
                mSuperPlayer.setTitle(url)//设置视频的titleName
                        .play(url);

                //设置play底部显示文本
                mSuperPlayer.setCaptionText(getActivity().getResources().getString(R.string.video, mFileName, programFileName));
                mTv.setText(getActivity().getResources().getString(R.string.video, mFileName, programFileName));
            }

            @Override
            public void longClick(final int position, int type, String programFileName, final String url) {
                final VideoFileNameBean bean = mVideoFileNameList.get(position);
                bean.setCollect(!bean.isCollect());
                bean.setName(programFileName);
                bean.setURL(url);

                ShareVideoBean shareVideoBean = (ShareVideoBean) loadFile(Contants.RadioCollect);
                //是选中的,
                if (bean.isCollect()) {
                    List<VideoFileNameBean> list = null;
                    if (shareVideoBean == null) {
                        shareVideoBean = new ShareVideoBean();
                        list = new ArrayList<>();
                    } else {
                        list = shareVideoBean.getList();
                    }
                    list.add(bean);
                    shareVideoBean.setList(list);
                    ToastUtil.showToast(mAppContext, (list.size() == 0) ? "没有收藏的节目" : "已经收藏了" + list.size() + "个节目");

                    //存入本地文件
                    SerializeManager.saveFile(shareVideoBean, Contants.RadioCollect);
                } else {
                    //是么有选中的(需要删除该收藏)
                    final ShareVideoBean finalShareVideoBean = shareVideoBean;
                    DialogUtils.showDialog(getActivity(), "删除", "确定要删除频道 " + bean.getName() + " 吗?", new DialogUtils.ShowDialogListener() {
                        @Override
                        public void onFixed() {
                            //确定删除
                            List<VideoFileNameBean> list = finalShareVideoBean.getList();
                            for (int i = 0; i < list.size(); i++) {
                                VideoFileNameBean nameBean = list.get(i);
                                if (nameBean.getURL().equals(url)) {
                                    list.remove(i);
                                }
                            }
                            finalShareVideoBean.setList(list);
                            ToastUtil.showToast(mAppContext, (list.size() == 0) ? "没有收藏的节目" : "还收藏了" + list.size() + "个节目");
                            //存入本地文件
                            SerializeManager.saveFile(finalShareVideoBean, Contants.RadioCollect);
                            //默认的节目列表名称
                            if (mTypePosition == 0) {
                                initDefaultData();
                            }
                            //刷新列表
                            mVideoFileNameAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onDismiss() {
                            //取消删除
                            bean.setCollect(true);
                            //刷新列表
                            mVideoFileNameAdapter.notifyDataSetChanged();
                        }
                    });
                }
                //刷新列表
                mVideoFileNameAdapter.notifyDataSetChanged();
            }
        });
    }


    /**
     * 设置节目类型列表item点击状态
     */
    private void setTypeListState() {
        FileNameBean bean;
        //在item被点击后,先将所有子item的点击状态设置为无
        for (int i = 0; i < mFileNameList.size(); i++) {
            bean = mFileNameList.get(i);
            bean.setUnfolded(false);
        }
        bean = mFileNameList.get(mTypePosition);
        bean.setUnfolded(true);
    }

    /**
     * 设置电视列表item的点击状态
     */
    private void setListItemState() {
        //在item被点击后,先将所有子item的点击状态设置为无
        for (int i = 0; i < mVideoFileNameList.size(); i++) {
            mVideoFileNameList.get(i).setUnfolded(false);
        }
        mVideoFileNameList.get(mTVListPosition).setUnfolded(true);
        //刷新列表
        mVideoFileNameAdapter.notifyDataSetChanged();
    }

    public void onEventMainThread(AnyEventType event) {
        switch (event.getType()) {
            case EventBusEvents.EVENT_VIDEO_START:
                //视频播放开始
                if (mSuperPlayer != null) {
                    mSuperPlayer.onResume();
                    if (null != mURL) {
                        mSuperPlayer.setTitle(mURL)//设置视频的titleName
                                .play(mURL);
                        //重新开始播放的时候,设置list列表的item选中状态
                        setTypeListState();
                        setListItemState();
                    }
                }
                break;
            case EventBusEvents.EVENT_VIDEO_STOP:
                //视频播放停止
                if (mSuperPlayer != null) {
                    mSuperPlayer.onDestroy();
                }
                break;
            case EventBusEvents.REFRESH_PROGRAM_LIST:

                break;
        }
    }

    /**
     * 设置videoPlay监听
     */
    private void initVideoPlayListener() {
        /**设置监听手机网络的变化**/
        mSuperPlayer.setNetChangeListener(true)
                /**实现网络变化的回调**/
                .setOnNetChangeListener(this)
                .onPrepared(new SuperPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared() {
                        /**监听视频是否已经准备完成开始播放。**/
                        /**设置屏幕可旋转**/
                        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                        videoState(1);
                    }
                }).onComplete(new Runnable() {
            @Override
            public void run() {
                /** 监听视频是否已经播放完成了。**/
                videoState(2);
            }
        }).onInfo(new SuperPlayer.OnInfoListener() {
            @Override
            public void onInfo(int what, int extra) {
                /**监听视频的相关信息。**/
                videoState(3);
            }
        }).onError(new SuperPlayer.OnErrorListener() {
            @Override
            public void onError(int what, int extra) {
                /**监听视频播放失败的回调**/
                videoState(4);
            }
        });
    }

    private void videoState(int i) {
        switch (i) {
            case 1:
                /**隐藏播放按钮,背景图片,以及视频时长,返回布局**/
                mIv.setVisibility(View.GONE);
                mPr.setVisibility(View.GONE);
                break;
            case 2:
                /**显示播放按钮,背景图片,以及视频时长,返回布局**/

                //隐藏loading
                mPr.setVisibility(View.GONE);
                //设置屏幕朝向-竖屏
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                //释放资源
                mSuperPlayer.release();
                break;
            case 3:
                /**视频相关信息**/
                break;
            case 4:
                /**视频播放失败**/
                ToastUtil.showToast(mAppContext, "播放失败!");
                mPr.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 网络链接监听类
     */
    @Override
    public void onWifi() {
        /**wifi状态播放视频**/
        if (!mSuperPlayer.isPlaying()) {
            mSuperPlayer.play(mURL, mCurrentPosition);
        }
    }

    public void onMobile() {
        if (DIALOG_SHOW)
            return;
        /**非wifi情况下,暂停播放**/
        mSuperPlayer.pause();
        /**当前视频播放的进度**/
        mCurrentPosition = mSuperPlayer.getCurrentPosition();
        /**弹出dialog提示用户当前网络非wifi**/

        DialogUtils.showDialog(getActivity(), "WIFI", "是不是要开启wifi?", new DialogUtils.ShowDialogListener() {
            @Override
            public void onFixed() {
                mSuperPlayer.play(mURL, mCurrentPosition);
                DIALOG_SHOW = false;
            }

            @Override
            public void onDismiss() {
                WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
                wifiManager.setWifiEnabled(true);
                DIALOG_SHOW = false;
            }
        });
        DIALOG_SHOW = true;
    }

    @Override
    public void onDisConnect() {
        ToastUtil.showToast(mAppContext, "网络链接断开");
    }

    @Override
    public void onNoAvailable() {
        ToastUtil.showToast(mAppContext, "无网络链接");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mSuperPlayer != null) {
            mSuperPlayer.onConfigurationChanged(newConfig);
        }
        HomeActivity activity = (HomeActivity) getActivity();
        //如果横屏,就设置viewPager距离底部的距离为0,否则为50dp
        if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_USER) {
            activity.setBottomState(true);
            mMenu.setVisibility(View.GONE);
        } else {
            activity.setBottomState(false);
            mMenu.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                //选择文件
                processTheSDCardFile(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 处理从sdcard加载进来的文件
     *
     * @param data
     */
    private void processTheSDCardFile(Intent data) {
        if (null == data){
            return;
        }
        Uri uri = data.getData();
        String path = FileUtils.getPath(mCtx, uri);

        SDCardFilePathBean sdCardBean = (SDCardFilePathBean) loadFile(Contants.SDCardPathBean);
        List<FileNameBean> fileNameBeenList = null;
        if (null != sdCardBean) {
            //获取其中的用户添加的文件名数据
            fileNameBeenList = sdCardBean.getmList();

            for (int i = 0; i < fileNameBeenList.size(); i++) {
                if (path.equals(fileNameBeenList.get(i).getPath())) {
                    //已经存储过这个文件
                    ToastUtil.showToast(mAppContext, "已经存在该文件");
                    return;
                }
            }

            FileNameBean bean = new FileNameBean();
            bean.setName(path.split("/")[path.split("/").length - 1]);
            bean.setPath(path);
            bean.setAssetsFile(false);
            fileNameBeenList.add(bean);
            //添加进去list
            sdCardBean.setmList(fileNameBeenList);
        }
        //将封装的bean存入本地.
        SerializeManager.saveFile(sdCardBean, Contants.SDCardPathBean);

        addFileNameList(fileNameBeenList);
    }

    /**
     * \
     * 添加sd文件路径到list
     */
    private void addFileNameList(List<FileNameBean> fileNameBeenList) {
        //先清空再添加
        mFileNameList.clear();
        mFileNameList.addAll(fileNameBeenList);
        mFileNameAdapter.notifyDataSetChanged();
        ToastUtil.showToast(mAppContext, "添加成功");
    }
}
